import { join } from 'path'
export function createDataServer() {
  const sqlite3 = require('sqlite3').verbose()
  const bodyParser = require('body-parser')
  const db_patn = join(__dirname, '../../resources/reginfos.sqlite3')
  const sqlite3_db = new sqlite3.Database(db_patn)

  const cors = require('cors')
  const express = require('express')
  const app_express = express()
  // const http = require('http').createServer(app_express);
  let data_port = 8080

  // 允许跨域
  app_express.use(cors())
  app_express.use(bodyParser.json())
  // app_express.use(function (req, res, next) {
  //   res.header('Access-Control-Allow-Origin','*')
  //   res.header('Access-Control-Allow-Headers','Content-Type')
  //   res.header('Access-Control-Allow-Methods','GET,POST,PUT,DELETE,OPTIONS')
  //   if (req.method == 'OPTIONS') res.sendStatus(200)
  //   else next()
  // })

  app_express.get('/', (req, res) => {
    // 设置文字编码为utf8，解决乱码
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    console.log('ok,成功')
    
    res.send('ok,成功')
  })
  app_express.get('/list', (req, res) => {
    sqlite3_db.all('SELECT * FROM keysAndCustomers', [], (err, rows) => {
      if (err) res.send(err)
      else res.send(rows)
    })
  })
  app_express.get('/list_regcode', (req, res) => {
    sqlite3_db.all(
      'SELECT rg.*, kc.customerName FROM regcodesGenerated rg JOIN keysAndCustomers kc ON rg.customerId = kc.customerId',
      [],
      (err, rows) => {
        // sqlite3_db.all('SELECT * FROM regcodesGenerated', [], (err, rows) => {
        if (err) res.send(err)
        else res.send(rows)
      }
    )
  })
  app_express.post('/add_regcode', (req, res) => {
    let { regcode, genetatedTime, expireTime, extendDays, secretKey, customerId } = req.body
    sqlite3_db.run(
      `INSERT INTO regcodesGenerated (regcode,genetatedTime,expireTime,extendDays,secretKey,customerId) VALUES (?,?,?,?,?,?)`,
      [regcode, genetatedTime, expireTime, extendDays, secretKey, customerId],
      (err, rows) => {
        if (err) res.send(err)
        else res.send(rows)
      }
    )
  })
  app_express.post('/add_secretkey', (req, res) => {
    let { customerId, customerSecKey, customerName, startTime } = req.body
    sqlite3_db.run(
      `INSERT INTO keysAndCustomers (customerId, customerSecKey, customerName, startTime) VALUES (?,?,?,?)`,
      [customerId, customerSecKey, customerName, startTime],
      (err, rows) => {
        if (err) res.send(err)
        else res.send(rows)
      }
    )
  })
  // const dbRouter = require(join(__dirname, '../'))
  // app_express.use('/db', require(join(__dirname, './router/db_router')))

  app_express.listen(data_port, () => {
    console.log(`Data server running at: http://localhost:${data_port}`)
  })
}
